package com.elinshaw.wordcount;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.HashMap;
import java.util.Map;

/**
 * 单词统计，并且实时获取词频前N的发射出去
 *
 * @author Administrator
 */
public class WordCountBolt extends BaseRichBolt {

    private static final long serialVersionUID = 2374950653902413273L;
    private OutputCollector outputcollector;
    private HashMap<String, Integer> counts;

    /**
     * bolt初始化方法，与spout的open()方法类似
     */
    @Override
    public void prepare(Map map, TopologyContext topologycontext, OutputCollector outputcollector) {
        this.outputcollector = outputcollector;
        this.counts = new HashMap<>();
    }

    /**
     * 接收Tuple数据进行单词计数处理
     */
    @Override
    public void execute(Tuple tuple) {
        //获取发送过来的单词
        String word = tuple.getStringByField("word");
        //添加这行代码的作用是看看值相等的word是不是同一个实例执行的，事实证明确实如此  
        //System.out.println(this + "====" + word);
        if (counts.containsKey(word)) {
            counts.put(word, counts.get(word) + 1);
        } else {
            counts.put(word, 1);
        }

        //发送单词和计数给下一个bolt对应字段word和count
        this.outputcollector.emit(new Values(word, counts.get(word)));
    }

    /**
     * 设置字段名称，对应emit(new Values(word, count))中的两个字段
     */
    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("word", "count"));
    }

}